import Vue from 'vue'
import VueRouter from 'vue-router'
import {Auth} from './resources'
import toastr from 'toastr'
import axios from 'axios'
import Home from './components/home.vue'
import Index from './components/index.vue'
import Index2 from './components/index2.vue'


Vue.use(VueRouter)

// 专门用来展示静态HTML文件的组件
const Html = {
  template: '<div v-html="html"></div>',
  data: () => ({
    html: ''
  }),
  beforeRouteEnter (to, from, next) {
    axios.get('/static/html/' + to.params.file).then(response => {
      next(vm => {
        vm.html = response.data
        vm.$nextTick(() => vm.$emit('loaded'))
      })
    })
  },
  beforeRouteUpdate (to, from, next) {
    this.$emit('loaded', 1)
    axios.get('/static/html/' + to.params.file).then(response => {
      this.html = response.data
      this.$nextTick(() => {
        this.$emit('loaded', 0)
        next()
      })
    })
  }
}
toastr.options.positionClass = 'toast-bottom-left'
toastr.options.containerId = 'toast-container'
toastr.options.newestOnTop = false
toastr.options.closeButton = true
toastr.options.extendedTimeOut = 100000 // How long the toast will display after a user hovers over it
toastr.options.timeOut = 100000 // How long the toast will display without user interaction

const routes = [
  {
    path: '/',
    component: Index,
    children: [
      {path: '', component: Home},
      {path: '/mobile', component: resolve => require(['./components/home-mobile.vue'], resolve)}
    ]
  },{
    path: '/child',
    component: Index2,
    children: [
      {path: '', component: Home},
      {path: '/mall', component: resolve => require(['./components/mall.vue'], resolve)},
      {path: '/teachers/:type?', component: resolve => require(['./components/teachers.vue'], resolve)},
      {path: '/teacher/:id', component: resolve => require(['./components/teacher.vue'], resolve)},
      {path: '/experience',component:resolve => require(['./components/experience.vue'],resolve)},
      {path: '/customer-save',component:resolve => require(['./components/customer-save.vue'],resolve)},
      {path: '/html/:file', component: Html}
    ]
  }
  // {path: '/login', component: resolve => require(['./components/login.vue'], resolve)},
  // {path: '/logout', beforeEnter: Auth.logout}
]

// 需要鉴权的路径
const permissive = ['/login', '/logout']

const router = new VueRouter({
  // mode: 'history',
  routes: routes,
  base: '/'
})

/*
beforeRouteEnter(to, form, next) {
  // 进入首页前先进行登录验证
  Auth.authorizationCheck().then(response => {
    next()
  }, response => {  // 登录验证操失败, 转到登录页并带上当前请求路径
    next('/login?from=' + to.path)
  })
},
*/
router.beforeEach((to, from, next) => {
  if (permissive.indexOf(to.path) != -1 && !Auth.isLogin()) {
    console.log('您需要先登录.')
    toastr.info('您需要先登录.')
    next({
      path: '/login',
      query: {redirect: to.path}
    })
  }
  return next()
})

export default router